package com.dszy.controller;

import com.dszy.entity.Clazz;
import com.dszy.service.ClazzService;
import com.dszy.util.DsJsonResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("clazz")
public class ClazzController {

    // 注入班级服务
    @Resource
    private ClazzService clazzService;

    /**
     * 查询全部学生记录
     * @param clazz
     * @return
     */
    @GetMapping
    public DsJsonResult queryAll(@RequestBody(required = false) Clazz clazz){
        return DsJsonResult.ok().setData(clazzService.queryAll(clazz));
    }

    /**
     * 按指定班号查询班级记录
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public DsJsonResult queryById(@PathVariable("id") int id){
        return DsJsonResult.ok().setData(clazzService.queryById(id));
    }

    /**
     * 新增班级记录
     * @param clazz
     * @return
     * 返回：新增成功后的班级记录
     */
    @PostMapping
    public DsJsonResult add(@RequestBody Clazz clazz){
        int num = clazzService.insert(clazz);
        if(num>0){
            return DsJsonResult.ok().setData(clazz);
        }else{
            return DsJsonResult.fail().setData("新增班级记录失败");
        }
    }

    /**
     * 修改班级记录
     * @param clazz
     * @return
     * 返回：修改成功后的班级记录
     */
    @PutMapping
    public DsJsonResult edit(@RequestBody Clazz clazz){
        int num = clazzService.update(clazz);
        if(num>0){
            return DsJsonResult.ok().setData(clazz);
        }else{
            return DsJsonResult.fail().setData("修改班级记录失败");
        }
    }

    /**
     * 按班号删除班级
     * @param id
     * @return
     * 返回：基于id查询到的班级信息
     */
    @DeleteMapping("/{id}")
    public DsJsonResult delete(@PathVariable("id") int id) {
        // 先查询记录，用于删除后返回记录
        Clazz clazz = clazzService.queryById(id);
        int num = clazzService.deleteById(id);
        if(num>0){
            return  DsJsonResult.ok().setData(clazz);
        }else{
            return DsJsonResult.fail().setData("删除失败");
        }
    }
}
